package gofunc

import (
	"crypto/md5"
	"fmt"
)

type StrFunc struct {
}

//将字符串转化求md5
func (self *StrFunc) Md5(in string) string {
	md5h := md5.New()
	md5h.Write([]byte(in))
	md5str := fmt.Sprintf("%x", md5h.Sum([]byte(""))) //md5
	return md5str
}

//字符串数组去重
func (self *StrFunc) Uniq(ls []string) []string {
	strInSlice := func(i string, list []string) bool {
		for _, v := range list {
			if v == i {
				return true
			}
		}
		return false
	}
	var Uniq []string
	for _, v := range ls {
		if !strInSlice(v, Uniq) {
			Uniq = append(Uniq, v)
		}
	}
	return Uniq
}

//截取字符串 start 起点下标 length 需要截取的长度
func (self *StrFunc) Substr(str string, start int, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}

	return string(rs[start:end])
}

//截取字符串 start 起点下标 end 终点下标(不包括)
func (self *StrFunc) Substr2(str string, start int, end int) string {
	rs := []rune(str)
	length := len(rs)

	if start < 0 || start > length {
		panic("start is wrong")
	}

	if end < 0 || end > length {
		panic("end is wrong")
	}

	return string(rs[start:end])
}

//返回字符在字符串数组的位置，没有找到返回-1
func (self *StrFunc) IndexOf(arry []string, value string) int {
	for k, v := range arry {
		if value == v {
			return k
		}
	}
	return -1
}

//_.without(["1", "2", "1", "0", "3", "1", "4"], "0", "1");
//=> ["2", "3", "4"]
//在字符串数组中去掉 某个值
func (self *StrFunc) Without(arry []string, withoutstr ...string) []string {
	var re []string
	for _, v := range arry {
		if self.IndexOf(withoutstr, v) != -1 {
			re = append(re, v)
		}
	}
	return re
}
